from flask import Flask,render_template,redirect,url_for
from flask import request
from Phonebook import Phonebook,DBSession

app=Flask(__name__)


@app.route('/')
def index():
    return redirect(url_for('userList'))

@app.route('/userList')
def userList():
    session=DBSession()
    user = session.query(Phonebook).all()
    return render_template('userList.html', lists = user)

@app.route('/addPhone')
def addPhone():
    return render_template('addPhone.html')

@app.route('/doAddPhone',methods=['POST'])
def doAddPhone():
    username = request.form['username']
    sex = request.form['sex']
    phonenumber = request.form['phonenumber']
    email = request.form['email']
    family_mem=Phonebook(name=username,sex=sex,phone=phonenumber,email=email)
    session=DBSession()
    #添加数据
    session.add(family_mem)
    session.commit()
    session.close()
    return redirect(url_for('userList'))

@app.route('/modifyPhone')
def modifyPhone():
	#获取get参数
    id = request.args.get('id') 
    session=DBSession()
    #查询数据
    user=session.query(Phonebook).filter(Phonebook.id==id).one()
    return render_template('modifyPhone.html', user = user)

@app.route('/doModifyPhone',methods=["POST"])
def doModifyPhone():
    id = request.args.get('id')
    username = request.form['username']
    sex = request.form['sex']
    phonenumber = request.form['phonenumber']
    email = request.form['email']
    session=DBSession() 
    #修改数据
    session.query(Phonebook).filter(Phonebook.id==id).update({Phonebook.name:username,Phonebook.sex:sex,Phonebook.phone:phonenumber,Phonebook.email:email})
    session.commit()
    return redirect(url_for('userList'))


@app.route('/deletePhone')
def deletePhone():
    id=request.args.get('id')
    session=DBSession()
    session.query(Phonebook).filter(Phonebook.id==id).delete()
    session.commit()
    return redirect(url_for('userList'))

@app.route('/queryPhone')
def queryPhone():
    return render_template('queryPhone.html')

@app.route('/doQueryPhone',methods=["POST"])
def doQueryPhone():
    username=request.form['username']
    session=DBSession()
    user=session.query(Phonebook).filter(Phonebook.name==username).all()
    session.commit()
    if user:
        return render_template('userList.html',lists=user,username=username)
    else:
        return '您查询的联系人不存在'

if __name__=='__main__':
    app.run(debug=True)

